package com.example.xiaozu.Fragment;

import static android.content.Context.MODE_PRIVATE;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.xiaozu.Adapter.ArticleAdapter;
import com.example.xiaozu.R;
import com.example.xiaozu.model.Article;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class HeadlinesFragment extends Fragment {
    private RecyclerView recyclerView;
    private ArticleAdapter adapter;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_headlines, container, false);
        recyclerView = view.findViewById(R.id.rv_articles);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        // 模拟数据
        List<Article> articles = new ArrayList<>();
        articles.add(new Article("1", "智慧农业助力大棚蓝莓抢“鲜”上市", "日前，旅顺口区现代农业生产发展服务中心积极行动，组织农技专家深入龙头街道王家村大连市果然好蓝莓种植基地，开展专业的蓝莓生产技术指导服务，精准解决生产过程中存在的技术难题，为蓝莓的丰产丰收保驾护航。", "大连晚报", new Date()));
        articles.add(new Article("2", "国内首创！南农研发“农业变形金刚””", "近日，位于南京六合农业基地里，南京农业大学工学院副院长郑恩来教授团队正在进行一场别开生面的“科技春耕”。记者在现场采访看到，随着无人驾驶拖拉机拖着小麦智能精准耕播复式作业机驶入田间，秸秆粉碎、旋耕整地、精量播种、变量施肥等工序一气呵成，展现出智慧农业的硬核实力。", "扬子晚报", new Date()));

        adapter = new ArticleAdapter(articles, article -> {
            Intent intent = new Intent(getActivity(), com.example.xiaozu.activity.ArticleDetailActivity.class);
            intent.putExtra("article", (Serializable) article);
            startActivity(intent);
        });
        recyclerView.setAdapter(adapter);
        return view;

    }

    private List<Article> loadArticles() {
        List<Article> articles = new ArrayList<>();
        SharedPreferences prefs = getContext().getSharedPreferences("articles", MODE_PRIVATE);

        // 获取所有以"article_"开头的key
        Map<String, ?> allEntries = prefs.getAll();
        for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
            if (entry.getKey().endsWith("_title")) {
                String id = entry.getKey().replace("_title", "");
                String title = (String) entry.getValue();
                String content = prefs.getString(id + "_content", "");
                String author = prefs.getString(id + "_author", "未知作者");
                long time = prefs.getLong(id + "_time", System.currentTimeMillis());

                articles.add(new Article(id, title, content, author, new Date(time)));
            }
        }
        return articles;
    }
}
